<?php
/**
 * Created by PhpStorm.
 * User: 崔海峰
 * Date: 2017/11/14
 * Time: 16:01
 */
/**
 * 功能函数
 * @param $str
 * @return mixed
 */
function ihtml_entity_decode($str)
{
    $str = str_replace('&nbsp;', '#nbsp;', $str);
    return str_replace('#nbsp;', '&nbsp;', html_entity_decode(urldecode($str)));
}

/**
 * 获取系统所有通知信息的集合
 * @param $template_type
 * @param $notify_type
 */
function getNoticeTemplateType($template_type,$notify_type){

    global $dou;
    $template_list = array();
    $sql = "SELECT * FROM ".$dou->table('notice_template_type')." WHERE (template_type = 'all' OR template_type = '{$template_type}') AND
             notify_type = '{$notify_type}'";
    $query = $dou->query($sql);
    while ($row = $dou->fetch_array($query)) {
        $template_list[] = $row;
    }
    return $template_list;
}


/**
 * 获取通知模板
 * @param $template_code
 * @param  $type
 */
function getNoticeTemplateDetail($template_code,$type){
    global $dou;
    $sql = "SELECT * FROM ".$dou->table('notice_template')." WHERE template_code = '{$template_code}' AND template_type = '{$type}'";
    $query = $dou->query($sql);
    return $dou->fetch_array($query);
}

/**
 * 获取模板的变量信息以及用于哪个模板
 * @param $template_code
 */
function getNoticeTemplateItem($template_code){
    global $dou,$_CFG;
    $sql = "SELECT * FROM ".$dou->table('notice_template_item')." WHERE FIND_IN_SET('{$template_code}',type_ids)";
    $query = $dou->query($sql);
    while ($row = $dou->fetch_array($query)) {

        $item_list[] = $row;
    }
    return $item_list;
}


/**
 * 更新通知模板消息
 * @param $shop_id
 * @param $template_type
 * @param $template_array
 * @param $notify_type
 */
function updateNoticeTemplate($template_type, $template_array,$notify_type){
    global $dou;
    $template_data = json_decode($template_array, true);
    foreach ($template_data as $template_obj) {
        $template_code = $template_obj["template_code"];
        $template_title = $template_obj["template_title"];
        $template_content = $template_obj["template_content"];
        $sign_name = $template_obj["sign_name"]?$template_obj["sign_name"]:'';
        $is_enable = $template_obj["is_enable"]?1:0;
        $notification_mode = $template_obj["notification_mode"];
        $template = getNoticeTemplateDetail($template_code,$template_type);
        if($template)
        {
            $modify_time = time();
            $sql = "UPDATE ".$dou->table('notice_template')." SET template_title = '{$template_title}',
                  template_content = '{$template_content}',sign_name = '{$sign_name}',is_enable = '{$is_enable}',
                  modify_time = '{$modify_time}',notification_mode = '{$notification_mode}'  WHERE template_type = '{$template_type}'AND notify_type = '{$notify_type}' AND template_code = '{$template_code}'";
            $dou->query($sql);
        }else{
//            //新增模板
//            $data = array(
//                "template_type" => $template_type,
//                "template_code" => $template_code,
//                "template_title" => $template_title,
//                "template_content" => $template_content,
//                "sign_name" => $sign_name,
//                "is_enable" => $is_enable,
//                "modify_time" => time(),
//                "notify_type" => $notify_type,
//                "notification_mode" => $notification_mode
//            );
//            pdo_insert('notice_template',$data);
        }

    }
}



/**
 * 阿里大于短信发送
 *
 * @param unknown $appkey
 * @param unknown $secret
 * @param unknown $signName
 * @param unknown $smsParam
 * @param unknown $send_mobile
 * @param unknown $template_code
 */
function aliSmsSend($appkey, $secret, $signName, $smsParam, $send_mobile, $template_code, $sms_type = 0)
{
    if ($sms_type == 0) {
// 旧用户发送短信
        return aliSmsSendOld($appkey, $secret, $signName, $smsParam, $send_mobile, $template_code);
    } else {
// 新用户发送短信
        return aliSmsSendNew($appkey, $secret, $signName, $smsParam, $send_mobile, $template_code);
    }
}

/**
 * 阿里大于旧用户发送短信
 *
 * @param unknown $appkey
 * @param unknown $secret
 * @param unknown $signName
 * @param unknown $smsParam
 * @param unknown $send_mobile
 * @param unknown $template_code
 * @return Ambigous <unknown, \ResultSet, mixed>
 */
function aliSmsSendOld($appkey, $secret, $signName, $smsParam, $send_mobile, $template_code)
{
    require_once ROOT_PATH . 'include/notify/alisms/TopSdk.php';
    $c = new TopClient();
    $c->appkey = $appkey;
    $c->secretKey = $secret;
    $req = new AlibabaAliqinFcSmsNumSendRequest();
    $req->setExtend("");
    $req->setSmsType("normal");
    $req->setSmsFreeSignName($signName);
    $req->setSmsParam($smsParam);
    $req->setRecNum($send_mobile);
    $req->setSmsTemplateCode($template_code);
    $result = $resp = $c->execute($req);
    return $result;
}

/**
 * 阿里大于新用户发送短信
 *
 * @param unknown $appkey
 * @param unknown $secret
 * @param unknown $signName
 * @param unknown $smsParam
 * @param unknown $send_mobile
 * @param unknown $template_code
 */
function aliSmsSendNew($appkey, $secret, $signName, $smsParam, $send_mobile, $template_code)
{
    require_once ROOT_PATH . 'include/notify/alisms_new/aliyun-php-sdk-core/Config.php';
    require_once ROOT_PATH . 'include/notify/alisms_new/SendSmsRequest.php';
// 短信API产品名
    $product = "Dysmsapi";
// 短信API产品域名
    $domain = "dysmsapi.aliyuncs.com";
// 暂时不支持多Region
    $region = "cn-hangzhou";
    $profile = DefaultProfile::getProfile($region, $appkey, $secret);
    DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
    $acsClient = new DefaultAcsClient($profile);

    $request = new SendSmsRequest();
// 必填-短信接收号码
    $request->setPhoneNumbers($send_mobile);
// 必填-短信签名
    $request->setSignName($signName);
// 必填-短信模板Code
    $request->setTemplateCode($template_code);
// 选填-假如模板中存在变量需要替换则为必填(JSON格式)
    $request->setTemplateParam($smsParam);
// 选填-发送短信流水号
    $request->setOutId("0");
// 发起访问请求
    $acsResponse = $acsClient->getAcsResponse($request);
    return $acsResponse;
}

/**
 * 处理阿里大鱼返回的数据
 * @param $result
 * @return array
 */
function dealAliSmsResult($result)
{

    global $_CFG;
    $deal_result = array();
    try {
        if ($_CFG['sms_user_type'] == 0) {
            #旧用户发送
            if (!empty($result)) {
                if (!isset($result->result)) {
                    $result = json_decode(json_encode($result), true);
                    #发送失败
                    $deal_result["code"] = $result["code"];
                    $deal_result["message"] = $result["msg"];
                } else {
                    #发送成功
                    $deal_result["code"] = 0;
                    $deal_result["message"] = "发送成功";
                }
            }
        } else {
            #新用户发送
            if (!empty($result)) {
                if ($result->Code == "OK") {
                    #发送成功
                    $deal_result["code"] = 0;
                    $deal_result["message"] = "发送成功";
                } else {
                    #发送失败
                    $deal_result["code"] = -1;
                    $deal_result["message"] = $result->Message;
                }
            }
        }
    } catch (\Exception $e) {
        $deal_result["code"] = -1;
        $deal_result["message"] = "发送失败!";
    }

    return $deal_result;
}